package com.lemon.smartsafetynew.web;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

/**
 * Created by Andrew on 2017/9/30.
 */

public class HtmlActivity extends SwipeBackActivity {

    private String mUrl = "";
    private int titleId;

    private LinearLayout mLayout;
    private WebView mWebView;

    private long mOldTime;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {

            if(bundle.containsKey(KeyConstants.KEY_HTML_URL)) {
                mUrl = bundle.getString(KeyConstants.KEY_HTML_URL);
            }

            if(bundle.containsKey(KeyConstants.KEY_TITLE_ID)) {
                titleId = bundle.getInt(KeyConstants.KEY_TITLE_ID, 0);
            }
        }

    }

    @Override
    protected void initTitle() {
        this.setBarTitle(titleId);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(HtmlActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_web;
    }

    @Override
    protected void initViews() {
        super.initViews();

        mLayout = (LinearLayout) findViewById(R.id.web_layout);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
                .MATCH_PARENT);
        mWebView = new Html5WebView(getApplicationContext());
        mWebView.setLayoutParams(params);
        mLayout.addView(mWebView);

        mWebView.loadUrl(mUrl);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mOldTime < 1500) {
                mWebView.clearHistory();
                mWebView.loadUrl(mUrl);
            } else if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                callFinish();
            }
            mOldTime = System.currentTimeMillis();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
